package com.gwt.boot.generator;

import com.alibaba.druid.pool.DruidDataSource;
import com.mybatisflex.codegen.Generator;
import com.mybatisflex.codegen.config.ColumnConfig;
import com.mybatisflex.codegen.config.GlobalConfig;

import java.util.Scanner;

/**
 * 实体类生成工具
 */
public class GeneratorForFlex {
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        String url = "jdbc:mysql://8.140.105.198:3306/gwtphoto";
        String userName = "gwtphoto";
        String password = "gwtphoto2024";
        doTable(url, userName, password, "com.gwt");
    }

    public static void doTable(String url, String userName, String password, String packagePath){
        //配置数据源
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);

        //创建配置内容，两种风格都可以。
        GlobalConfig globalConfig = createGlobalConfigUseStyle(packagePath);
        //通过 datasource 和 globalConfig 创建代码生成器
        Generator generator = new Generator(dataSource, globalConfig);
        //生成代码
        generator.generate();
    }

    public static GlobalConfig createGlobalConfigUseStyle(String packagePath) {
        //创建配置内容
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setAuthor(scanner("作者名称"));
        //设置根包
        globalConfig.setBasePackage(packagePath + "." + scanner("包名"));
        //设置表前缀和只生成哪些表
        globalConfig.setTablePrefix("sys_", "t_");
        String tables = scanner("表名，多个英文逗号分隔,所有输入 *");
        if (!"*".equals(tables)){
            //setGenerateTable 未配置时，生成所有表
            globalConfig.setGenerateTable(tables.split(","));
        }
        //设置生成 entity 并启用 Lombok
        globalConfig.setEntityGenerateEnable(true);
        globalConfig.setEntityWithLombok(true);
        globalConfig.isEntityWithSwagger();
        globalConfig.setEntityWithSwagger(false);
        //设置项目的JDK版本，项目的JDK为14及以上时建议设置该项，小于14则可以不设置
        globalConfig.setEntityJdkVersion(8);
        //globalConfig.enableTableDef();
        globalConfig.setControllerGenerateEnable(true);
        globalConfig.setServiceGenerateEnable(true);
        //设置生成 mapper
        globalConfig.setMapperGenerateEnable(true);
        globalConfig.setMapperXmlGenerateEnable(true);
        globalConfig.setEntityPackage(globalConfig.getBasePackage() + ".po");
        globalConfig.setMapperPackage(globalConfig.getBasePackage() + ".dao");
        //可以单独配置某个列
        ColumnConfig columnConfig = new ColumnConfig();
        columnConfig.setColumnName("tenant_id");
        columnConfig.setLarge(true);
        columnConfig.setVersion(true);
        globalConfig.setColumnConfig("tb_account", columnConfig);
        return globalConfig;
    }

    private static String scanner(String msg){
        System.out.print("请输入" + msg + "：");
        return scanner.nextLine();
    }
}